package book;

/**
 * 测试notify，只能一次唤醒一个wait线程
 * @author：涂有
 * @date 2017年2月28日 下午4:00:19
 */
public class WaitNotifyTest {
	
	static class A implements Runnable{
		
		Object lock;
		private int count;
		
		public A(Object lock){
			
			this.lock = lock;
		}

		@Override
		public void run() {

			synchronized (lock) {
			
				System.out.println("开始等待:" + Thread.currentThread().getName());
				System.out.println(count++);
				try {
					lock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(count++);
				System.out.println("结束等待:" + Thread.currentThread().getName());
			}
		}
	}
	
	static class B implements Runnable{
		
		Object lock;
		
		public B(Object lock){
			
			this.lock = lock;
		}
		
		@Override
		public void run() {
			
			for(int i = 0; i < 3; i++){
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (lock) {
					
					lock.notify();
					System.out.println("通知");
				}
			}
		}
	}

	public static void main(String[] args) {
		
		Object lock = new Object();
		A a = new A(lock);
		Thread a1 = new Thread(a);
		Thread a2 = new Thread(a);
		Thread a3 = new Thread(a);
		Thread b1 = new Thread(new B(lock));
		
		a1.start();
		a2.start();
		a3.start();
		b1.start();
	}
}
